// 导入 axios
import axios from 'axios'
export default {
  namespaced: true,
  state: () => ({
    cart: []
  }),
  mutations: {
    // cart 参数接收 actions 中 getCartList 方法提交过来的 res.data.list
    updateCartList (state, cart) {
      state.cart = cart
    },
    // 修改单选状态
    updataGoodsState (state, payload) {
      const index = state.cart.findIndex((item) => item.id === payload.id)
      state.cart[index].goods_state = payload.value
    },
    // 修改 count 数量
    updataGoodsCount (state, payload) {
      const index = state.cart.findIndex((item) => item.id === payload.id)
      state.cart[index].good_count = payload.value
    },
    // 全选控制小选
    updateAllState (state, payload) {
      state.cart.forEach((item) => (item.goods_state = payload))
    }
  },
  actions: {
    async getCartList (context) {
      const res = await axios.get('https://www.escook.cn/api/cart')
      //   console.log(res.data.list)
      // 提交给 mutations 中的 updateCartList 方法处理
      context.commit('updateCartList', res.data.list)
    }
  },
  getters: {
    // 总价
    allPrice (state) {
      return state.cart
        .filter((item) => item.goods_state)
        .reduce((sum, item) => (sum += item.goods_count * item.goods_price), 0)
    },
    // 总数量
    allCount (state) {
      return state.cart
        .filter((item) => item.goods_state)
        .reduce((sum, item) => (sum += item.goods_count), 0)
    }
  }
}
